<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="table-ref">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" v-if="formShow" />
      </template>
      <template #toolbar_btns>
        <div class="w-[100%]">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="组织维度" name="department"></el-tab-pane>
            <el-tab-pane label="品类维度" name="category"></el-tab-pane>
          </el-tabs>
          <div class="w-[100%] flex gap-x-3 mt-[8px]">
            <div class="flex-1">
              <el-button @click="importHandleClick">
                <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 </span>
              </el-button>
            </div>

            <FieldSelectBtn :fieldSelectConfig="fieldSelectConfig" @submit="query" />
          </div>
        </div>
      </template>
    </VTable>
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
import { onMounted, ref, toRefs } from "vue"

import { inventoryTurnoverSummary } from "@/api/salesInventory"
const tableRef = ref()
import FieldSelectBtn from "@/views/salesInventory/components/FieldSelectBtn.vue"

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = {}
  DerivedCenterRef.value.open({
    tag_name: "performance_indicators",
    condition,
  })
}
const activeName = ref("department")
const handleClick = () => {
  tableRef?.value.query()
}
const formData = ref({})
// 查询
const query = () => {
  tableRef?.value.query()
}

const formShow = ref(false)
import { getAloneEnum } from "@/utils/enumUtils"
//获取下拉数据
onMounted(async () => {
  let oneKeys = ["wmsAttribute", "warehouse"]
  let optData = await getAloneEnum(oneKeys)
  oneKeys.forEach((key) => {
    originOption.value[key] = optData?.[key]
  })
  setTimeout(() => {
    formShow.value = true
  }, 100)
})

// 枚举 数据
const originOption = ref({})

const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  {
    field: "warehouse_id",
    type: "select",
    originField: "warehouse",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库" },
    ...publicStyle,
  },
  {
    field: "warehouse_attribute",
    type: "select",
    originField: "wmsAttribute",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库属性" },
    ...publicStyle,
  },

  {
    field: "department_id",
    type: "cascaderNew",
    cascaderType: "department",
    placeholder: "组织维度",
    cascaderProps: {},
    ...publicStyle,
  },
  {
    field: "category",
    type: "cascaderNew",
    cascaderType: "category",
    placeholder: "产品品类",
    ...publicStyle,
  },
  {
    field: "date",
    type: "dateTimeRangeNorm",
    itemProps: {
      type: "daterange",
      valueFormat: "YYYY-MM-DD",
    },
    style: { width: "300px" },
  },

  {
    field: "dimension",
    type: "radio",
    options: {
      data: [
        { label: "周维度", value: 1 },
        { label: "月维度", value: 2 },
      ],
    },
    change: (e) => {
      tableRef?.value?.$table.loadColumn([])
      nextTick(() => query())
    },
    ...publicStyle,
  },
  {
    field: "sku",
    placeholder: "SKU",
    type: "textarea",
    style: { width: "200px" },
  },
])
const configColumns = ref([
  { title: "金额", field: "value1", width: 100 },
  { title: "环比", field: "value2", width: 100 },
])

// 初始化时间
import { parseTime } from "@/utils/ruoyi"
const initDate = () => {
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 30)
  return [new Date(temp.setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 0))].map((d) => parseTime(d, "{y}-{m}-{d}"))
}

// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      dimension: 2,
      date: initDate(),
    },
  },

  columnConfig: {
    resizable: true,
  },
  pagerConfig: null,
  // rowConfig: { height: 60 },
  border: "outer",
  columns: [{ type: "seq", title: "序号", width: 60 }],

  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        console.log("query")
        console.log(form)
        let params = {
          page: page.pageNum,
          page_num: page.pageSize,
          ...initForm(form),
          // dimension: 2,
          // by: "department",
          // date: ["2024-03", "2024-04"],
        }

        return await queryList(params)
      },
    },
  },
  treeConfig: {
    hasChildField: "hasChild",
    lazy: true,
    loadMethod: ({ row }) => {
      return returnRow(row.child)
    },
  },

  showFooter: true,
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (column.type == "seq") return ""
        if (column.field === totalKey.value) {
          return "合计"
        } else {
          return sumNum(data, column.field)
        }
      }),

      columns.map((column, columnIndex) => {
        if (column.type == "seq") return ""
        if (column.field === totalKey.value) {
          return "品牌类合计"
        } else {
          return 2
          // return sumNum(data, column.field)
        }
      }),
      columns.map((column, columnIndex) => {
        if (column.type == "seq") return ""
        if (column.field === totalKey.value) {
          return "贸易类合计"
        } else {
          return 3
          // return sumNum(data, column.field)
        }
      }),
    ]
  },
})
// 合计
const sumNum = (list, field) => {
  let count = 0
  let fields = field?.split(".")
  let getObjKeys = (data) => {
    return fields.reduce((pre, cur) => pre[cur], data)
  }
  list.forEach((item) => {
    count += Number(getObjKeys(item, fields) || 0)
  })
  return count
}
import { filterColumns } from "@/views/salesInventory/components/method.js"
const totalKey = ref("")
const tabColumn = {
  category: { field: "category_name", title: "产品品类", minWidth: 200, treeNode: true },
  department: { field: "department_name", title: "组织", minWidth: 200, treeNode: true },
}
let headerColumns = [
  { label: "销售额（RMB）", key: "sales_data" },
  { label: "库存金额（RMB）", key: "inventory_data" },
  { label: "库存投入变化", key: "change_data" },
  { label: "库销比", key: "percent_data" },
  { label: "周转天数", key: "turnover_data" },
]
const queryList = async (params) => {
  tableRef?.value?.$table.reloadData([])
  let rps = await inventoryTurnoverSummary(params)
  let { date, res } = initTableData(params.dimension, rps)
  let aconfigColumns = []
  headerColumns.forEach((item) => {
    let data = { field: item.key, title: item.label, align: "center", children: [] }
    if ("sales_data,inventory_data".includes(item.key)) {
      // 销售额（RMB） 库存金额（RMB）
      data.children = date.map((d) => ({
        title: d,
        width: 100,
        children: [
          { title: "金额", field: `${item.key}.${d}.amount`, fieldShow: `${item.key}.amount`, width: 100 },
          { title: "环比", field: `${item.key}.${d}.diff_amount`, fieldShow: `${item.key}.diff_amount`, width: 100 },
        ],
      }))
    } else if (item.key == "change_data") {
      // 库存投入变化
      data.children = [
        { title: "BOH", field: "change_data.boh_amount", width: 80 },
        { title: "变化", field: "change_data.diff_amount", width: 80 },
      ]
    } else if (item.key == "percent_data") {
      // 库销比
      data.children = date.map((d) => ({
        title: d,
        width: 100,
        field: `${item.key}.${d}.percent`,
        fieldShow: `${item.key}.percent`,
      }))
    } else if (item.key == "turnover_data") {
      // 周转天数
      data.children = date.map((d) => ({
        title: d,
        width: 100,
        children: [
          { title: "目标天数（月）", field: `${item.key}.${d}.target_days`, fieldShow: `${item.key}.target_days`, width: 120 },
          { title: "周转天数", field: `${item.key}.${d}.turnover_days`, fieldShow: `${item.key}.turnover_days`, width: 100 },
        ],
      }))
    }
    aconfigColumns.push(data)
  })
  let columnsData = [...tableOptins.columns, tabColumn[activeName.value], ...aconfigColumns]

  fieldSelectConfig.value.columns = JSON.parse(JSON.stringify(columnsData)).map((v) => {
    if ("sales_data,inventory_data,turnover_data,percent_data".includes(v.field)) {
      v.children = v.children[0].children
    }
    return v
  })
  const { columns, key } = filterColumns(columnsData, fieldSelectConfig.value.columnsShow)
  totalKey.value = key
  nextTick(() => {
    tableRef?.value?.$table.loadColumn(columns)
    tableRef?.value.updateScroll()
  })
  return res
}
const initTableData = (dimension = 1, res) => {
  let date = res.data?.[0]?.inventory_data.map((v) => v.date)
  res.data.forEach((item) => {
    item.child = item.department_child || item.category_child
    item.hasChild = !!item.child?.length
    item.sales_data = Object.fromEntries(item?.sales_data.map((v) => [v.date, { ...v }]))
    item.inventory_data = Object.fromEntries(item?.inventory_data.map((v) => [v.date, { ...v }]))
    item.percent_data = Object.fromEntries(item?.percent_data.map((v) => [v.date, { ...v }]))
    item.turnover_data = Object.fromEntries(item?.turnover_data.map((v) => [v.date, { ...v }]))
  })
  return { date, res }
}

const returnRow = async (child) => {
  let params = {
    ...initForm(tableRef?.value.getQueryForm()),
  }
  if (activeName.value == "department") {
    params.department_id = child
  } else {
    params.category = child
  }
  let rps = await inventoryTurnoverSummary(params)
  // 表格数据格式重组
  let { date, res } = initTableData(params.dimension, rps)
  return res.data
}
// 组装查询条件
const initForm = (form) => {
  let keys = ["sku", "order_number"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
    form[key] = form[key]?.map((v) => v.trim())
  })
  form.by = activeName.value
  return form
}
const fieldSelectConfig = ref({
  save: "turnover",
  columnsShow: [],
  columns: [],
})
</script>
<style lang="scss" scoped>
:deep(.vxe-header--row:nth-child(2)) {
  .vxe-header--column {
    // background: #eff3fe !important;
    background: var(--base-table-hover-bg-color);
  }
}

:deep(.vx-table__content) {
  // background: pink;
  height: 100%;
  .vxe-grid {
    // background: pink;
    height: 100%;
  }
}
// :deep(.vxe-body--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }
// :deep(.vxe-header--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }
// :deep(.vxe-footer--column) {
//   border-left: 1px solid #e6e7e9;
//   border-bottom: 1px solid #e6e7e9;
// }

:deep(.vxe-body--column) {
  border-left: 1px solid var(--base-link-color);
  border-bottom: 1px solid var(--base-link-color);
}
:deep(.vxe-header--column) {
  border-left: 1px solid var(--base-link-color);
  border-bottom: 1px solid var(--base-link-color);
}
:deep(.vxe-footer--column) {
  // border-left: 1px solid var(--base-link-color);
  // border-bottom: 1px solid var(--base-link-color);
  border-left: 1px solid var(--base-border-color);
  border-bottom: 1px solid var(--base-border-color);
}

:deep(.vxe-grid) {
}

:deep(.vx-table__form-content) {
  background-image: none;
}

.table-ref {
  // background: #f5f5f5;
  background: var(--base-color);
  :deep(.vx-table__form) {
    // margin-bottom: 8px;
  }
  :deep(.vx-table__content) {
    margin-top: 8px;
    // background: #fff;
    background: var(--base-color);
    border-radius: 6px;
    .vxe-buttons--wrapper {
      margin-right: -0.75rem;
    }
  }
  :deep(.vxe-footer--row) {
    // background: #eff3fe;
    background: var(--base-table-hover-bg-color);
  }
}
</style>
